import {
  reqCartList,
  reqDeleteCartById,
  reqUpdateCheckedByid,
} from "@/api/shopcart";

export default {
  namespaced: true,
  state: {
    cartList: [],
  },
  mutations: {
    GETCARTLIST(state, cartList) {
      state.cartList = cartList;
    },
  },
  actions: {
    async getCartList({ commit }) {
      let result = await reqCartList();
      console.log(result);
      if (result.code == 200) {
        commit("GETCARTLIST", result.data);
      }
    },
    // eslint-disable-next-line no-unused-vars
    async deleteId({ commit }, skuId) {
      let result = await reqDeleteCartById(skuId);
      console.log(result);
      if (result.code == 200) {
        return "ok";
      } else {
        return Promise.reject(new Error("faile"));
      }
    },
    // eslint-disable-next-line no-unused-vars
    async updateCheckedById({ commit }, { skuId, isChecked }) {
      let result = await reqUpdateCheckedByid(skuId, isChecked);
      console.log(result);
      if (result.code == 200) {
        return "ok";
      } else {
        return Promise.reject(new Error("faile"));
      }
    },
    deleteAllChecked({ dispatch, getters }) {
      let PromiseAll = [];
      //   getters.cartList.cartInfoList.map((item) => {
      //     if (item.isChecked == 1) {
      //       let promise = dispatch("deleteId", item.skuId);
      //       PromiseAll.push(promise);
      //     }
      //     return PromiseAll
      //   });
      getters.cartList.cartInfoList
        .filter((item) => item.isChecked == 1)
        .forEach((item) => {
          let promise=dispatch("deleteId", item.skuId);

          //将每一次返回的Promise添加到数组当中
          PromiseAll.push(promise);
        });

      return Promise.all(PromiseAll);
    },
    //修改全部产品的状态
    updateAllCartIsChecked({ dispatch, state }, isChecked) {
      //数组
      let promiseAll = [];
      state.cartList[0].cartInfoList.forEach((item) => {
        let promise = dispatch("updateCheckedById", {
          skuId: item.skuId,
          isChecked,
        });
        promiseAll.push(promise);
      });
      //最终返回结果
      return Promise.all(promiseAll);
    },
  },
  getters: {
    cartList(state) {
      return state.cartList[0] || {};
    },
  },
};
